import pandas as pd
from matplotlib import pyplot as plt
import matplotlib as mpl
from sklearn.linear_model import LinearRegression
import numpy as np

mpl.rcParams['font.sans-serif'] = ['Simhei']
mpl.rcParams['axes.unicode_minus'] = False
data = pd.read_csv('D:\\新建文件夹\\221042Y131韩奇龙-python数据挖掘课程设计\\python.csv')
data.info()
data[["order_id", "product_id", "category_id", "user_id", "category_code"]] = data[
    ["order_id", "product_id", "category_id", "user_id", "category_code"]].astype("object")

data["date"] = data["event_time"].apply(lambda x: x.split(' ')[0])
data["month"] = data["event_time"].apply(lambda x: x.split(' ')[0]).apply(lambda x: x.split('-')[1])
data["hour"] = data["event_time"].apply(lambda x: x.split(' ')[1]).apply(lambda x: x.split(':')[0])
data["category"] = data["category_code"].apply(lambda x: str(x).split('.')[0])
data["date"] = pd.to_datetime(data["date"])
data["hour"] = data["hour"].astype("int64")

data.duplicated().any()
data.drop_duplicates(inplace=True)

data.isnull().sum()
data.drop(data[data["date"] < "2020-04-01"].index, inplace=True)
ads = data.dropna(axis=0, how="any", inplace=False)
ads.notnull().sum()

date_group = ads.groupby("month")["order_id"].count()
_x = date_group.index
_y = date_group.values
plt.figure(figsize=(12, 6), dpi=80)
plt.plot(_x, _y, color="b")
x_lable = ["{}".format(i) for i in range(4, 12)]
plt.xticks(_x, x_lable, size=12)
plt.title("4-11月产品整体销量")
plt.xlabel("月份")
plt.ylabel("销量")
plt.show()

U_price = ads.groupby("month").agg({"price": 'sum', "user_id": 'nunique'})
U_price["Unit_Price"] = U_price["price"] / (U_price["user_id"])
U_price["Unit_Price"].plot(kind="line", figsize=(12, 6), color="g")
for i, j in zip(range(len(ads["month"])), U_price["Unit_Price"].values):
    plt.text(i, j + 50, "%.0f" % j)
plt.title("4-11月产品客单价")
plt.xlabel("月份")
plt.ylabel("单价")
plt.show()

cat_brand = ads.groupby(["brand", "category"])["price"].sum().sort_values(ascending=False)[:20]
cat_brand = cat_brand.reset_index(level=[0, 1])
cat_brand = pd.pivot_table(cat_brand, index='brand', columns='category', values='price')
cat_brand.plot(kind='bar', figsize=(12, 6), legend='1', rot=315)
plt.title("按品牌和类别统计销售额")
plt.xlabel("品牌")
plt.ylabel("销售额")
plt.show()

cat_brand = ads.groupby(["month", "category"])["price"].sum().sort_values(ascending=False)[:30]
month_cat = cat_brand.reset_index(level=[0, 1])
month_cat = pd.pivot_table(month_cat, index='month', columns='category', values='price')
month_cat.plot(kind='bar', figsize=(12, 6), rot=360, legend='1')
plt.title("按月份和类别统计销售额")
plt.xlabel("月份")
plt.ylabel("销售额")
plt.show()

sales_cat = ads.groupby(["category"])["price"].sum().sort_values(ascending=False)[:6]
plt.figure(figsize=(12, 6), dpi=80)
sales_cat.plot(kind="pie", autopct="%1.1f%%", colors=['red', 'yellowgreen', 'lightskyblue', 'yellow', 'b', 'g'])
plt.title("按类别统计销售额")
plt.show()

user_pay_freq = ads.groupby("user_id").nunique()["event_time"]
user_pay_amount = ads.groupby("user_id")["price"].sum()
plt.figure(figsize=(12, 6), dpi=80)
x_user = user_pay_freq.values
y_user = user_pay_amount.values
plt.scatter(x_user, y_user, color="pink")
plt.title("用户消费频率与消费总金额关系散点图")
plt.xlabel("消费频率")
plt.ylabel("消费总金额")
plt.show()

first_buy = ads.groupby("user_id")["month"].min().value_counts()
first_buy.plot(kind="bar", rot=360, color="r", figsize=(12, 6))
plt.title("用户首次购买月份的统计图")
plt.xlabel("月份")
plt.ylabel("人数")
plt.show()

last_buy = ads.groupby("user_id")["month"].max().value_counts()
last_buy.plot(kind="bar", rot=360, color="r", figsize=(12, 6))
plt.title("用户最后购买月份的统计图")
plt.xlabel("月份")
plt.ylabel("人数")
plt.show()

per = ads.groupby("user_id")["date"].agg(['min', 'max'])
no_per = (per['min'] == per['max']).value_counts()
no_per.plot(kind="pie", labels=["新用户", "老用户"], autopct='%.2f%%')
plt.title("新老用户占比统计图")
plt.show()

ads['month'] = pd.to_numeric(ads['month'], errors='coerce').astype(int)
months_for_training = [4, 5, 6, 7, 8, 9, 10]
X_train = np.array(months_for_training).reshape(-1, 1)
y_train = ads[ads['month'].isin(months_for_training)].groupby('month')['order_id'].count().values
model = LinearRegression()
model.fit(X_train, y_train)
X_predict = np.array([6]).reshape(-1, 1)
y_predict = model.predict(X_predict)

print(f"预测的6月份订单数量为: {y_predict[0]}")

plt.scatter(X_train, y_train, color='blue', label='实际数据')
plt.plot(X_train, model.predict(X_train), color='red', linewidth=2, label='模型预测')
plt.scatter(X_predict, y_predict, color='green', label='预测6月份')
plt.xlabel('月份')
plt.ylabel('订单数量')
plt.title('订单数量预测')
plt.legend()
plt.show()